import React, { useState, useEffect, useRef } from 'react';
import { Input, Table, Button, Space, Checkbox, Modal, Typography } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import EmptyPage from '@/components/empty/EmptyPage';

interface LinkItem {
  key: string;
  link: string;
  name: string;
}

const LinkTable: React.FC = () => {
  const [links, setLinks] = useState<LinkItem[]>([]);
  const [inputValue, setInputValue] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [renameModalVisible, setRenameModalVisible] = useState<boolean>(false);
  const [renameKey, setRenameKey] = useState<string | null>(null);
  const [newName, setNewName] = useState<string>('');
  const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
  const [deleteKey, setDeleteKey] = useState<string | null>(null);
  const [containerHeight, setContainerHeight] = useState<number | null>(null);

  useEffect(() => {
    const height = window.innerHeight - 400
    setContainerHeight(height);
  }, []);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && inputValue.trim()) {
      const newLink: LinkItem = {
        key: Date.now().toString(),
        link: inputValue.trim(),
        name: inputValue.trim().split('/').pop() || 'Untitled',
      };
      setLinks([...links, newLink]);
      setInputValue('');
    }
  };

  const handleRename = (key: string) => {
    const link = links.find((link) => link.key === key);
    if (link) {
      setNewName(link.name);
      setRenameKey(key);
      setRenameModalVisible(true);
    }
  };

  const handleRenameConfirm = () => {
    if (renameKey) {
      setLinks(
        links.map((link) =>
          link.key === renameKey ? { ...link, name: newName } : link
        )
      );
      setRenameModalVisible(false);
      setRenameKey(null);
    }
  };

  const handleRenameCancel = () => {
    setRenameModalVisible(false);
    setRenameKey(null);
  };

  const handleDelete = (key: string) => {
    setDeleteKey(key);
    setDeleteModalVisible(true);
  };

  const handleDeleteConfirm = () => {
    if (deleteKey) {
      setLinks(links.filter((link) => link.key !== deleteKey));
      setDeleteModalVisible(false);
      setDeleteKey(null);
    }
  };

  const handleDeleteCancel = () => {
    setDeleteModalVisible(false);
    setDeleteKey(null);
  };

  const handleSelectChange = (selectedKeys: React.Key[]) => {
    setSelectedRowKeys(selectedKeys);
  };

  const handleSelectAll = (e: any) => {
    if (e.target.checked) {
      const newSelectedRowKeys = links.map((link) => link.key);
      setSelectedRowKeys(newSelectedRowKeys);
    } else {
      setSelectedRowKeys([]);
    }
  };

  const handleDeleteSelected = () => {
    setLinks(links.filter((link) => !selectedRowKeys.includes(link.key)));
    setSelectedRowKeys([]);
  };

  const columns: ColumnsType<LinkItem> = [
    {
      title: 'Link',
      dataIndex: 'link',
      key: 'link',
      ellipsis: true,
      render: (text: string) => (
        <a href={text} target="_blank" rel="noopener noreferrer">
          {text}
        </a>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true
    },
    {
      title: 'Operation',
      key: 'operation',
      align: 'right',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleRename(record.key)}>
            <EditOutlined />
          </Button>
          <Button type="link" danger onClick={() => handleDelete(record.key)}>
            <DeleteOutlined />
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Input
        placeholder="输入或粘贴网址，按键盘Enter键确定，多个网址可继续输入"
        value={inputValue}
        onChange={handleInputChange}
        onPressEnter={handleInputEnter}
        style={{ height: 200, borderRadius: 20, border: '1px solid #d9d9d9' }}
      />
      <div
        style={{
          padding: '20px',
          marginTop: 16,
          borderRadius: 20,
          border: '1px solid #d9d9d9',
          height: containerHeight ? `${containerHeight}px` : '100%',
          overflow: 'auto',
        }}
      >
        {links.length > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16, paddingLeft: 8, paddingRight: 16 }}>
            <Checkbox
              indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < links.length}
              checked={selectedRowKeys.length === links.length}
              onChange={handleSelectAll}
            >
              待导入 ({links.length})
            </Checkbox>
            <Button
              type="link"
              danger
              onClick={handleDeleteSelected}
              style={{ marginLeft: 'auto' }}
            >
              <DeleteOutlined />
            </Button>
          </div>
        )}
        {/* {links.length > 0 ?  */}
        <Table
          dataSource={links}
          columns={columns}
          rowSelection={{
            selectedRowKeys,
            onChange: handleSelectChange,
            type: 'checkbox',
          }}
          pagination={false}
          showHeader={false}
        />
        {/* :
        <EmptyPage description="还没有资料，成功上传，AI学习后才能使用哦~" fontSize='300px' classname='mt-10' />} */}
      </div>

      <Modal
        title={
          <div style={{ textAlign: 'center', width: '100%' }}>
              重命名
          </div>
        }
        open={renameModalVisible}
        onOk={handleRenameConfirm}
        onCancel={handleRenameCancel}
        okText="确定"
        cancelText="取消"
        closable={false}
        width={300}
        centered
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size="middle">
              <Button onClick={handleRenameCancel}>取消</Button>
              <Button type="primary" onClick={handleRenameConfirm}>确定</Button>
            </Space>
          </div>
        }
      >
        <Input
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
        />
      </Modal>

      <Modal
        open={deleteModalVisible}
        onOk={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        okText="删除"
        width={300}
        closable={false}
        cancelText="取消"
        centered
        okButtonProps={{ danger: true }}
        footer={
          <div style={{ textAlign: 'center' }}>
            <Space size="middle">
              <Button onClick={handleDeleteCancel}>取消</Button>
              <Button type="primary" danger onClick={handleDeleteConfirm}>删除</Button>
            </Space>
          </div>
        }
      >
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50px' }}>
          <p style={{ textAlign: 'center' }}>确定要删除该数据源吗？</p>
        </div>
      </Modal>
    </div>
  );
};

export default LinkTable;